package com.izkml.mlyun.hotreload.websocket;

import cn.hutool.json.JSONUtil;
import com.izkml.mlyun.hotreload.debug.protocol.ResultVo;
import com.izkml.mlyun.hotreload.enums.ErrorEnums;
import com.izkml.mlyun.hotreload.enums.ResultTypeEnums;
import com.izkml.mlyun.hotreload.websocket.message.SendMessage;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
public class WebSocketUtil {

    public static void sendSuccess(WebSocketSession session) {
        try {
            SendMessage sendMessage = new SendMessage();
            session.sendMessage(new TextMessage(JSONUtil.toJsonStr(sendMessage)));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void sendSuccess(WebSocketSession session, ResultVo result) {
        try {
            SendMessage sendMessage = new SendMessage(result);
            session.sendMessage(new TextMessage(JSONUtil.toJsonStr(sendMessage)));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void sendError(WebSocketSession session, ErrorEnums errorEnums) {
        sendError(session, errorEnums, "");
    }

    public static void sendError(WebSocketSession session, ErrorEnums errorEnums, String message) {
        try {
            SendMessage sendMessage = new SendMessage(errorEnums.getCode(), errorEnums.getMessage() + " "+ message);
            session.sendMessage(new TextMessage(JSONUtil.toJsonStr(sendMessage)));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
